<template>
  <div class="ai-chat-page">
    <el-breadcrumb separator="/" style="margin-bottom: 16px;">
      <el-breadcrumb-item to="/home">{{ $t('menu.home') }}</el-breadcrumb-item>
      <el-breadcrumb-item>{{ $t('aiChat.title') }}</el-breadcrumb-item>
    </el-breadcrumb>
    
    <div class="chat-container">
      <!-- 聊天头部 -->
      <div class="chat-header">
        <div class="chat-title">{{ $t('aiChat.title') }}</div>
        <div class="header-actions">
          <el-button size="small" text @click="clearHistory">
            <el-icon><Delete /></el-icon>
            <span>{{ $t('aiChat.clearChat') }}</span>
          </el-button>
          <el-button size="small" text @click="showSettings = true">
            <el-icon><Setting /></el-icon>
            <span>{{ $t('common.settings') }}</span>
          </el-button>
        </div>
      </div>

      <!-- 聊天消息区域 -->
      <div class="chat-messages" ref="messagesContainer">
        <div 
          v-for="(message, index) in messages" 
          :key="index"
          :class="['chat-message', message.role]"
        >
          <div class="message-inner">
            <img 
              v-if="message.role === 'ai'" 
              :src="aiAvatar" 
              alt="AI" 
              class="avatar"
            />
            <div class="message-content">
              <span v-if="message.role === 'ai'" class="role">{{ $t('aiChat.assistant') }}</span>
              {{ message.content }}
            </div>
            <img 
              v-if="message.role === 'user'" 
              :src="userAvatar" 
              alt="User" 
              class="avatar-input"
            />
          </div>
        </div>

        <!-- AI正在输入... -->
        <div v-if="isSending" class="chat-message ai">
          <div class="message-inner">
            <img :src="aiAvatar" alt="AI" class="avatar" />
            <div class="message-content">
              <span class="role">{{ $t('aiChat.assistant') }}</span>
              {{ $t('aiChat.thinking') }}...
            </div>
          </div>
        </div>

        <!-- 欢迎消息 -->
        <div v-if="messages.length === 0 && !isSending" class="welcome-message">
          <el-icon :size="48" color="#409eff"><ChatDotRound /></el-icon>
          <h3>{{ $t('aiChat.welcomeMessage') }}</h3>
        </div>
      </div>

    <!-- 输入区域 -->
    <div class="chat-input-area">
      <textarea
        ref="inputRef"
        v-model="inputMessage"
        :placeholder="$t('aiChat.placeholder')"
        class="chat-input"
        @keydown="handleKeyDown"
        :disabled="isSending"
      ></textarea>
      <button 
        class="send-btn"
        @click="sendMessage"
        :disabled="!inputMessage.trim() || isSending"
      >
        {{ isSending ? $t('aiChat.thinking') : $t('aiChat.send') }}
      </button>
    </div>
    </div>

    <!-- 设置对话框 -->
    <el-dialog v-model="showSettings" :title="$t('common.settings')" width="500px">
      <el-form label-width="120px">
        <el-form-item :label="$t('aiChat.saveHistory')">
          <el-switch v-model="saveHistory" />
        </el-form-item>
      </el-form>
      <template #footer>
        <el-button @click="showSettings = false">{{ $t('common.cancel') }}</el-button>
        <el-button type="primary" @click="applySettings">{{ $t('common.confirm') }}</el-button>
      </template>
    </el-dialog>
  </div>
</template>

<script setup>
import { ref, nextTick, onMounted, watch } from 'vue';
import { ElMessage, ElMessageBox } from 'element-plus';
import { ChatDotRound, Delete, Setting } from '@element-plus/icons-vue';
import { useI18n } from 'vue-i18n';
import api from '@/api';

const { t } = useI18n();

// 消息列表
const messages = ref([]);
const inputMessage = ref('');
const isSending = ref(false);
const messagesContainer = ref(null);
const inputRef = ref(null);

// 设置
const showSettings = ref(false);
const saveHistory = ref(true);

// 头像 - 参考系统设置页面的亮色图标风格
const userAvatar = ref('');
const aiAvatar = ref('');

// 初始化
onMounted(() => {
  loadHistory();
});

// 监听消息变化，自动滚动到底部
watch(messages, () => {
  nextTick(() => {
    scrollToBottom();
  });
}, { deep: true });

// 处理键盘事件 - Enter发送，Ctrl+Enter换行
function handleKeyDown(e) {
  if (e.key === 'Enter' && !e.ctrlKey && !e.shiftKey) {
    e.preventDefault();
    sendMessage();
  }
}

// 发送消息
async function sendMessage() {
  const content = inputMessage.value.trim();
  if (!content || isSending.value) return;
  
  // 添加用户消息
  addMessage('user', content);
  inputMessage.value = '';
  
  // 标记发送中
  isSending.value = true;
  
  try {
    // 调用真实的AI API
    const response = await api.system.aiChat(content);
    
    // 处理响应
    if (response && response.data) {
      let aiResponse = '';
      
      // 处理不同的响应格式
      if (typeof response.data === 'string') {
        aiResponse = response.data;
      } else if (response.data.message) {
        aiResponse = response.data.message;
      } else if (response.data.content) {
        aiResponse = response.data.content;
      } else if (response.data.reply) {
        aiResponse = response.data.reply;
      } else {
        aiResponse = JSON.stringify(response.data);
      }
      
      // 添加AI回复
      addMessage('ai', aiResponse);
    } else {
      throw new Error('无效的响应格式');
    }
  } catch (error) {
    console.error('AI回复错误:', error);
    ElMessage.error(t('aiChat.requestFailed'));
    
    // 添加错误消息
    addMessage('ai', t('aiChat.requestFailed'));
  } finally {
    isSending.value = false;
    
    // 发送完成后，聚焦回输入框
    nextTick(() => {
      focusInput();
    });
  }
}

// 添加消息
function addMessage(role, content) {
  messages.value.push({
    role,
    content,
    timestamp: new Date()
  });
  
  if (saveHistory.value) {
    saveHistoryToStorage();
  }
}

// 清空历史
function clearHistory() {
  ElMessageBox.confirm('确定要清空所有聊天记录吗？', '提示', {
    confirmButtonText: t('common.confirm'),
    cancelButtonText: t('common.cancel'),
    type: 'warning'
  }).then(() => {
    messages.value = [];
    localStorage.removeItem('ai_chat_history');
    ElMessage.success(t('aiChat.chatCleared'));
  }).catch(() => {});
}

// 应用设置
function applySettings() {
  showSettings.value = false;
  ElMessage.success(t('common.success'));
  
  if (saveHistory.value) {
    saveHistoryToStorage();
  } else {
    localStorage.removeItem('ai_chat_history');
  }
}

// 滚动到底部
function scrollToBottom() {
  if (messagesContainer.value) {
    messagesContainer.value.scrollTop = messagesContainer.value.scrollHeight;
  }
}

// 保存历史到本地存储
function saveHistoryToStorage() {
  try {
    localStorage.setItem('ai_chat_history', JSON.stringify(messages.value));
  } catch (error) {
    console.error('保存历史失败:', error);
  }
}

// 从本地存储加载历史
function loadHistory() {
  try {
    const saved = localStorage.getItem('ai_chat_history');
    if (saved && saveHistory.value) {
      const parsed = JSON.parse(saved);
      messages.value = parsed.map(msg => ({
        ...msg,
        timestamp: new Date(msg.timestamp)
      }));
    }
  } catch (error) {
    console.error('加载历史失败:', error);
  }
}

// 聚焦输入框
function focusInput() {
  if (inputRef.value) {
    inputRef.value.focus();
  }
}
</script>

<style scoped lang="scss" src="@/styles/Chat.scss"></style>
